import React, {useEffect, useRef} from "react";
import { ResizeMode, Video} from "expo-av";
import styles from "./video-preview.style";
import {useRoute} from "@react-navigation/native";
import * as ScreenOrientation from "expo-screen-orientation";
import {OrientationLock} from "expo-screen-orientation";
import {activateKeepAwakeAsync, deactivateKeepAwake, useKeepAwake} from "expo-keep-awake";
import {View} from "react-native";

interface VideoPreviewerRouteProps {
    uri: string;
}

export default function VideoPreviewer() {
    const route = useRoute()
    const {uri} = route.params as VideoPreviewerRouteProps
    const playing = useRef<boolean>(false)

    useKeepAwake(); //保持唤醒
    useEffect(() => {
        activateKeepAwakeAsync();  //防止观看视频时屏幕休眠
        ScreenOrientation.unlockAsync(); // 解锁屏幕方向，允许旋转
        // 监听屏幕方向变化
        const listenOrientation = () => {
            return ScreenOrientation.addOrientationChangeListener((event) => {
                console.log(event);
            })
        };
        const listener = listenOrientation();
        return () => {
            ScreenOrientation.removeOrientationChangeListener(listener); // 移除屏幕方向变化监听
            ScreenOrientation.lockAsync(OrientationLock.DEFAULT); // 锁定屏幕方向
            deactivateKeepAwake(); // 卸载保持唤醒
        }
    }, []);

    return (
        <View>
            <Video

                source={{uri}}
                style={styles.video}
                resizeMode={ResizeMode.CONTAIN}
                shouldPlay
                useNativeControls
                onPlaybackStatusUpdate={async (status) => {
                    if (status.isLoaded) {
                        if (status.didJustFinish) {
                            if (playing.current) {
                                await deactivateKeepAwake(); // 卸载保持唤醒
                                playing.current = false;
                            }
                        } else if (status.isPlaying) {
                            if (!playing.current) {
                                playing.current = true;
                                await activateKeepAwakeAsync();  //防止观看视频时屏幕休眠
                            }
                        } else {
                            if (playing.current) {
                                await deactivateKeepAwake(); // 卸载保持唤醒
                                playing.current = false;
                            }
                        }
                    }
                }}
            />
        </View>
    )
}